× Lesson 1 Lesson 2 Lesson 3 Lesson 4 Lesson 5 Lesson 6 Lesson 7 Lesson 8 Lesson 9 Lesson 10 Lesson 11 Lesson 12 Lesson 13 Lesson 14 Lesson 15 Lesson 16 Lesson 17 Lesson 18 Lesson 19 Lesson 20 Lesson 21 Lesson 22 Lesson 23 Lesson 24 Lesson 25 Mini Lesson 1 Mini Lesson 2 Mini Lesson 3 Mini Lesson 4 Mini Lesson 5

Lessons

Mini Lesson 3: Lambda Functions

A lambda function are closely related to a regular function, however there are a couple differences. First, you don't set a name when you create a lambda function, you either use it in a return statement or make it a variable. Secondly, you can only have one expression, rather than the limitless amount of expressions you can have in a regular function.

Here's the basic syntax for a lambda function:

squared = lambda x: x ** 2

print(squared(2))

This would output for as we are using the variable name to call the lambda function. The x is our parameter, as it is followed by the colon, and note that you can half multiple parameters just like regular functions. The expression following the colon uses the argument passed, which in our case is 2, to square it, and we print out the outcome.

I want to show you one more example of lambda functions, this time inside of a regular function:

def multiplyby(x):

return lambda a: a * x

double = multiplyby(2)

triple = multiplyby(3)

print(double(10))

print(triple(10))

First, we defined a regular function called multiplyby, which has one parameter, which would return the value that the a lambda outputs. The expression in the lambda will multiple its own parameter a by the multiplyby's parameter x. Next, we set the word double equal to the multiplyby with 2 passed as the argument, and the word triple equal to the the multiplyby with 3 passed as the argument. Last, we printed out the variable double with the argument 10, and the same for the variable triple.

The argument passed in the multiplyby() correspended to the x in the lambda function, while the argument passed in the variable names correspended to the lambda's parameter as.